package model;

import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import util.ImageUtil;

public class SpriteStore {
	/** The single instance of this class */
	private static SpriteStore single = new SpriteStore();
	private static Logger logger;
	
	public static SpriteStore get() {
		return single;
	}

	private HashMap<String, Sprite> sprites = new HashMap<String, Sprite>();	

	public Sprite cloneSprite(Sprite spriteSrc){
		BufferedImage bufferedImageClone = ImageUtil.cloneBufferedImage(spriteSrc.getImage());
		return new Sprite(bufferedImageClone);
	}
	
	public Sprite getSprite(String ref) {		
		logger=Logger.getLogger(this.getClass().getName());


		if (sprites.get(ref) != null) {			
			return cloneSprite(sprites.get(ref));
		}

		BufferedImage sourceImage = null;
		URL url = this.getClass().getClassLoader().getResource(ref);	
		logger.info("Reading image " + ref + " from URL");
		try {  			  
			sourceImage = ImageIO.read(url);
		} catch (Exception e) {  
			e.printStackTrace();  
		}  

		Sprite sprite = new Sprite(sourceImage);
		sprites.put(ref,sprite);

		return cloneSprite(sprite);
	}
}